package thread.test2;


public class WaitNotifyTest extends Thread {

    private Object lock = new Object();//定义对象锁

    private volatile int threadSwitch = 1;//控制等待的开关

    private String id;//线程id

    public WaitNotifyTest(String id) {  this.id = id; }

    @Override
    public void run() {
        while (true) {
            synchronized (lock) { //先获取锁在调用wait()
                try {
                    Thread.sleep(100);
                    System.out.println("run id=" + id);
                    if (threadSwitch == 2) {  lock.wait();  }
                } catch (InterruptedException e) { e.printStackTrace(); }
            }
        }
    }

    public void off() {  this.threadSwitch = 2;  }

    public void on() {
        synchronized (lock) { //先获取锁在调用notifyAll
            this.threadSwitch = 1;
            lock.notifyAll();
            System.out.println("唤醒id=" + id);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyTest t1 = new WaitNotifyTest("1");
        WaitNotifyTest t2 = new WaitNotifyTest("2");
        //启动两个线程
        t1.start();
        t2.start();
        Thread.sleep(1000);
        //使线程进入等待状态
        t1.off();
        t2.off();
        Thread.sleep(1000);
        //唤醒线程1
        t1.on();
    }
}
